<template>
  <div class="middleView">
    <!-- 告警信息 -->
    <div class="alarmInfor" :class="{ anim: animate == true }">
      <p v-for="alarm in alarms" :key="alarm.id">
        {{ alarm.alarmInfor }}
      </p>
    </div>
    <!-- 监控画面 -->
    <div class="videoBox">
      <div class="videoImg">
        <div class="videoView">
          <video
            controls
            muted
            autoplay
            id="videoFlv"
            style="width: 99.4%; height: 99.4%"
            class="video-js"
          ></video>
        </div>
      </div>
    </div>
    <!-- 电子地图正面 -->
    <div class="map">
      <div class="mapBox1">
        <div class="path">
          <img src="../../../images/luchen.png" alt="" />
          <p style="margin-left: 4px">总路程 :</p>
          <p style="margin-left: 4px">500m</p>
        </div>
        <div class="speed">
          <img src="../../../images/sudu.png" alt="" />
          <p style="margin-left: 4px">速度 :</p>
          <p style="margin-left: 4px">{{ this.linearX }}m/s</p>
        </div>
        <div class="stopBtn">
          <img
            src="../../../images/停.png"
            alt=""
            style="width: 38px; height: 38px"
          />
        </div>
        <div class="electric">
          <img src="../../../images/dianliang.png" alt="" />
          <p style="margin-left: 4px">电量 :</p>
          <p style="margin-left: 4px">{{ this.dcdl }}%</p>
        </div>
        <div class="qyd">
          <img src="../../../images/quyang.png" alt="" />
          <p style="margin-left: 4px">取样点 :</p>
          <p style="margin-left: 4px">5个</p>
        </div>
      </div>
      <div class="mapBox2">
        <canvas id="canvas">不支持canvas</canvas>
      </div>
    </div>
  </div>
</template>
<script>
import { getAlarmList } from "@/api/cyRobot/home";
export default {
  name: "MiddleView",
  data() {
    return {
      timer: null,
      timer1: null,
      //是否显示video框背景
      videoBg: false,
      alarm: [],
      alarms: [{ alarmtime: "暂无数据" }],
      // 警告数据中间
      animate: false,
      queryparm: {
        robot_id: localStorage.getItem("robotId"),
      },
      //机器人运行速度
      linearX: "",
      //电量
      dcdl: "",
      webRtcServer: null, //摄像头服务
      robotCamIP: localStorage.getItem("robotCamIP"),
      rtsp: "",
      cvs: "",
      ctx: "",
      startTime: "",
      timer: 0,
      points: [], //已经运动过的数据
      //当前运动点位置
      animatePoint: {
        x: 0,
        y: 0,
      },
      nextPointIndex: 1, //下一个运动点的index
      routes: [
        { x: 10, y: 15 },
        { x: 10, y: 52 },
        { x: 142, y: 52 },
        { x: 142, y: 72 },
        { x: 180, y: 72 },
        { x: 252, y: 72 },
        { x: 280, y: 72 },
      ],
      //videoUrl: ''
    };
  },
  created() {
    //监听全局事件总线上的'updateRobotId'事件
    this.$bus.$on("updateRobotCamIP", (newCamIP) => {
      this.robotCamIP = newCamIP;
      //切换机器人就播放
      this.spbf();
    });
    // 监听 'linearX' 事件
    this.$bus.$on("linearX", (value) => {
      this.linearX = value;
    });

    // 监听 'dcdl' 事件
    this.$bus.$on("dcdl", (value) => {
      this.dcdl = value;
    });
  },
  mounted() {
    this.timer = setInterval(() => {
      this.alarmList();
    }, 2000);
    setInterval(this.scroll, 5000); //初始化滚动警告数据
    this.spbf();
    this.toDraw();
  },
  beforeDestroy() {
    //销毁全局事件总线
    this.$bus.$off("updateRobotCamIP");
    this.$bus.$off("linearX");
    this.$bus.$off("dcdl");

    if (this.timer) {
      clearInterval(this.timer);
    }
    if (this.timer1) {
      clearInterval(this.timer1);
    }
    if (this.webRtcServer != null) {
      this.webRtcServer.disconnect();
      this.webRtcServer = null;
    }
  },
  methods: {
    // 插件播放
    spbf() {
      //console.log("视频地址", localStorage.getItem("robotCamIP"));
      //this.videoBg = true;
      //this.videoUrl = 'https://www.w3school.com.cn/i/movie.mp4'
      if (
        localStorage.getItem("robotCamIP") != "" &&
        localStorage.getItem("robotCamIP") != null
      ) {
        this.videoBg = true;
        // 确保 videoFlv 元素已经存在
        this.$nextTick(() => {
          const videoElementH = document.getElementById("videoFlv");
          if (videoElementH) {
            this.webRtcServer = new WebRtcStreamer(
              "videoFlv",
              location.protocol + "//127.0.0.1:8000"
            );
            this.webRtcServer.connect(
              "rtsp://" + localStorage.getItem("robotCamIP") + ":554/video1"
            );
            this.rtsp =
              "rtsp://" + localStorage.getItem("robotCamIP") + ":554/video1";
            console.log("视频地址", this.rtsp);
          } else {
            console.error("videoFlv 元素不存在");
          }
        });
      } else {
        this.videoBg = false;
      }
    },
    //中间滚动警告数据
    scroll() {
      this.animate = true; // 因为在消息向上滚动的时候需要添加css3过渡动画，所以这里需要设置true
      this.timer1 = setTimeout(() => {
        //  这里直接使用了es6的箭头函数，省去了处理this指向偏移问题
        this.alarms.push(this.alarms[0]); // 将数组的第一个元素添加到数组的
        this.alarms.shift(); //删除数组的第一个元素
        this.animate = false; // margin-top 为0 的时候取消过渡动画，实现无缝滚动
      }, 3000);
    },
    alarmList() {
      getAlarmList(this.queryparm).then((response) => {
        this.alarm = response.rows;
        //console.log('告警数据',this.alarm)
        this.alarms = [];
        this.alarms = response.rows.map((item) => {
          return {
            alarmInfor: item.alarminfo,
          };
        });
      });
    },
    init(routes) {
      this.animatePoint = { x: 0, y: 0 };
      this.nextPointIndex = 1;
      this.ctx.clearRect(0, 0, this.cvs.clientWidth, this.cvs.clientHeight);
      if (routes.length > 0) {
        this.points.push({
          x: routes[0].x,
          y: routes[0].y,
        });
        this.animatePoint = {
          x: routes[0].x,
          y: routes[0].y,
        };
        this.drawPoint(routes[0].x, routes[0].y);
      }
      if (routes.length > 1) {
        this.startTimer();
      }
    },
    startTimer() {
      this.startTime = new Date().getTime();
      if (this.routes.length > 1) {
        this.clearTimer();
        this.animate1();
      }
    },
    clearTimer() {
      window.cancelAnimationFrame(this.timer);
    },
    animate1() {
      this.timer = window.requestAnimationFrame(this.animate1);
      this.startMove();
    },
    startMove() {
      let routes = this.routes;
      let targetDistance = Math.sqrt(
        Math.pow(
          routes[this.nextPointIndex - 1].x - routes[this.nextPointIndex].x,
          2
        ) +
          Math.pow(
            routes[this.nextPointIndex - 1].y - routes[this.nextPointIndex].y,
            2
          )
      );

      let currentDistance = Math.sqrt(
        Math.pow(routes[this.nextPointIndex - 1].x - this.animatePoint.x, 2) +
          Math.pow(routes[this.nextPointIndex - 1].y - this.animatePoint.y, 2)
      );

      if (currentDistance >= targetDistance) {
        //利用运动距离与目标距离, 判断运动的点是否超过下一个目标点, 超过了就重置下一个点
        this.startTime = new Date().getTime();

        this.points[this.nextPointIndex] = {
          x: routes[this.nextPointIndex].x,
          y: routes[this.nextPointIndex].y,
        };

        this.animatePoint = {
          x: routes[this.nextPointIndex].x,
          y: routes[this.nextPointIndex].y,
        };

        this.nextPointIndex++;

        this.clearTimer();
        if (this.nextPointIndex <= routes.length - 1) {
          setTimeout(() => {
            this.startTimer();
          }, 500);
        }

        //重绘
        this.ctx.clearRect(0, 0, this.cvs.clientWidth, this.cvs.clientHeight);
        this.drawPolygon(this.points);
        this.drawPoint(this.animatePoint.x, this.animatePoint.y, "yellow");
        return;
      }

      if (this.nextPointIndex > routes.length - 1) {
        //轨迹运动结束后, 关闭timer
        this.clearTimer();

        this.animatePoint = {
          x: routes[routes.length - 1].x,
          y: routes[routes.length - 1].y,
        };
      } else {
        let speed = 0.25;

        let deltaTime = new Date().getTime() - this.startTime;
        let deltaDistance = deltaTime * speed;
        let rate = deltaDistance / targetDistance;
        let x =
          routes[this.nextPointIndex - 1].x +
          (routes[this.nextPointIndex].x - routes[this.nextPointIndex - 1].x) *
            rate;
        let y =
          routes[this.nextPointIndex - 1].y +
          (routes[this.nextPointIndex].y - routes[this.nextPointIndex - 1].y) *
            rate;

        this.animatePoint.x = x;
        this.animatePoint.y = y;

        //重绘, 将animatePoint设为轨迹的下一个点, 以达到动态的效果
        this.points[this.nextPointIndex] = {
          x: this.animatePoint.x,
          y: this.animatePoint.y,
        };
        this.ctx.clearRect(0, 0, this.cvs.clientWidth, this.cvs.clientHeight);
        this.drawPolygon(this.points);
        this.drawPoint(this.animatePoint.x, this.animatePoint.y, "red");
      }
    },
    drawPoint(x, y) {
      var iconImage = new Image();
      iconImage.src = require("../../../images/xiao.png");
      const ys = y - 1.5;
      this.ctx.drawImage(iconImage, x, ys, 15, 15);
    },
    drawPolygon(points) {
      //绘制轨迹
      this.ctx.clearRect(0, 0, this.cvs.clientWidth, this.cvs.clientHeight);
      this.ctx.strokeStyle = "#1DEFFF";
      this.ctx.shadowColor = "#1DEFFF";
      this.ctx.shadowBlur = 10;
      this.ctx.lineWidth = 3;
      this.ctx.beginPath();
      this.ctx.moveTo(points[0].x, points[0].y);
      let i = 1,
        len = points.length;
      for (; i < len; i++) {
        this.ctx.lineTo(points[i].x, points[i].y);
      }
      this.ctx.stroke();
      //去除之前的点
      // let j = 0;
      // for (; j < len - 1; j++) {
      //   this.drawPoint(points[j].x, points[j].y);
      // }
    },
    //点击绘制
    toDraw() {
      this.cvs = document.getElementById("canvas");
      this.ctx = this.cvs.getContext("2d");
      this.points = [];
      this.init(this.routes);
    },
  },
};
</script>
<style lang="scss" scoped>
* {
  padding: 0;
  margin: 0;
}

.middleView {
  width: 40%;
  height: calc(100vh - 40px - 50px);
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;

  //告警信息
  .alarmInfor {
    width: 98%;
    height: 35px;
    margin-bottom: 2px;
    overflow: hidden;

    > p {
      padding-left: 50px;
      font-family: Source Han Sans CN;
      font-weight: 500;
      font-size: 13px;
      color: #ffd200;
      height: 35px;
      line-height: 35px;
      background-image: url(../../../images/alarm.png);
      background-repeat: no-repeat;
      background-size: 100% 100%;
    }

    .anim {
      transition: all 0.5s;
      margin-top: -30px;
    }
  }

  //监控画面
  .videoBox {
    width: 98%;
    height: 42%;

    .videoImg {
      width: 99.8%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      background-image: url(../../../images/shiping.png);
      background-repeat: no-repeat;
      background-size: 100% 100%;

      //background-color: aquamarine;
      .videoView {
        width: 100%;
        height: 100% !important;
        display: flex;
        justify-content: center;
        align-items: center;
        background-image: url(../../../images/jiankong.png);
        background-repeat: no-repeat;
        background-position: center center;
      }

      .video-js {
        background-color: rgb(1 5 43);
        object-fit: fill;
        //隐藏video播放按钮
      }

      video {
        pointer-events: none;
      }

      //隐藏video播放按钮
      video::-webkit-media-controls-play-button {
        display: none !important;
      }

      //隐藏video音量进度条
      video::-webkit-media-controls-volume-slider {
        display: none !important;
      }

      //隐藏video音量按钮
      video::-webkit-media-controls-mute-button {
        display: none !important;
      }

      video::-webkit-media-controls-toggle-closed-captions-button {
        display: none !important;
      }

      //隐藏当前时间
      video::-webkit-media-controls-current-time-display {
        display: none !important;
      }

      //隐藏剩余时间
      video::-webkit-media-controls-time-remaining-display {
        display: none !important;
      }

      //隐藏进度条
      video::-webkit-media-controls-timeline {
        display: none !important;
      }

      //更多选项
      video::-internal-media-controls-overflow-button {
        display: none !important;
      }
    }
  }

  //电子地图
  .map {
    width: 98%;
    height: 50%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .mapBox1 {
      width: 100%;
      height: 15%;
      display: flex;
      align-items: center;
      justify-content: space-around;

      .path {
        height: 100%;
        width: 25%;
        display: flex;
        align-items: center;
        font-family: Source Han Sans CN;
        font-weight: 500;
        font-size: 12px;
        color: #ffffff;
      }

      .speed {
        height: 100%;
        width: 20%;
        display: flex;
        align-items: center;
        font-family: Source Han Sans CN;
        font-weight: 500;
        font-size: 12px;
        color: #ffffff;
      }

      .electric {
        height: 100%;
        width: 20%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-family: Source Han Sans CN;
        font-weight: 500;
        font-size: 12px;
        color: #ffffff;
      }

      .qyd {
        height: 100%;
        width: 20%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-family: Source Han Sans CN;
        font-weight: 500;
        font-size: 12px;
        color: #ffffff;
      }

      .stopBtn {
        height: 100%;
        width: 10%;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }

    .mapBox2 {
      width: 100%;
      height: 85%;
      display: flex;
      justify-content: center;
      align-items: center;

      //background-color: cornflowerblue;
      #canvas {
        width: 100%;
        height: 100%;
        background-image: url(../../../images/gj.jpg);
        background-size: 100% 100%;
        background-repeat: no-repeat;
      }
    }
  }
}
</style>
